"""实例配置管理
"""

import json
import atexit
import logging
from pathlib import Path
from typing import List, Literal
from ..config import config_storage_path


class AppConfig(object):

    _instance = None

    # 单例模式
    def __new__(cls, *args, **kw):
        if cls._instance is None:
            cls._instance = object.__new__(cls, *args, **kw)
        return cls._instance
        # 程序退出时保存配置到配置文件 /tmp/config.json

    @property
    def config_file(self):
        return Path(config_storage_path(), "config.json")

    def sync_to_disk(self):
        """ """
        json_str = json.dumps(self.__dict__, indent=4)
        with open(self.config_file, "w") as f:
            logging.warning("save configs to '{}' ".format(self.config_file))
            f.write(json_str)

    def update_config_item(self, config_item_name: str, config_item_value):
        """更新配置项"""
        self.__dict__[config_item_name] = config_item_value
        self.sync_to_disk()

    def register_config_item(self, config_item_name: str, config_item_value):
        """注册配置项"""
        if config_item_name not in self.__dict__:
            self.__dict__[config_item_name] = config_item_value
            self.sync_to_disk()

    def get_config_item(self, config_item_name: str):
        """获取配置项"""
        return self.__dict__[config_item_name]

    def __init__(self):
        self.docs_indexing_paths: List[str] = []
        self.exit_when_close: bool = False
        self.docx_default_software: Literal["word", "wps"] = "word"
        self.pptx_default_software: Literal["powerpoint", "wps"] = "powerpoint"
        """如果配置文件存在就用配置文件中的值，覆盖默认值；
        在这个过程中如果遇到异常就保持默认值。程序退出时持久到到配置到文件。"""
        if self.config_file.exists():
            try:
                with open(self.config_file, encoding="utf8") as f:
                    json_data = json.loads(f.read())
                    self.__dict__.update(json_data)
                    print("updated configs to", self.__dict__)
            except Exception as err:
                import traceback

                traceback.print_exc()
        else:
            logging.warn(
                "config file '{}' not exists. will use default values.".format(
                    self.config_file
                )
            )

        atexit.register(self.sync_to_disk)
        # if self.paths is None:
        #     self.paths = []


app_config = AppConfig()
